@using System.Web
@using Microsoft.AspNetCore.Mvc.TagHelpers
@model IEnumerable<string>
@{
    ViewData["Title"] = "List files";
}

@if (!Model.Any())
{
    <div class="alert alert-info" role="alert">
        <h2 class="alert-heading">No files found</h2>
        <p>
            <a class="" asp-area="" asp-controller="Files" asp-action="Upload">Upload Files</a>
        </p>
    </div>
}
else
{
    int rowCounter = 0;
    <h2>Files found in network share</h2>
    <table class="table" id="uploadedFiles">
        <thead>
        <tr>
            <th>File path</th>
            <th></th>
        </tr>
        </thead>
        <tbody>
        @foreach (string file in Model)
        {
            string rowId = $"file{rowCounter}";
            rowCounter++;
            <tr id="@(rowId)">
                <td>@file</td>
                <td>
                    <a class="btn btn-danger" onclick="deleteFile('@HttpUtility.UrlEncode(file)', '@(rowId)')">Delete file</a>
                </td>
            </tr>
        }
        </tbody>
    </table>
}

<script>
    function deleteFile(fileName, rowId) {
        $.ajax({
            url: "/files/delete?fileToDelete=" + encodeURIComponent(fileName),
            method: "DELETE",
            success: function(result) {
                console.log(result);
                $("#" + rowId).remove();
                if ($("#uploadedFiles tbody tr").length === 0) {
                    $("#uploadedFiles tbody").append('<tr><td colspan="2">All files have been deleted. <a href="@Url.Action("Upload", "Files")">Upload files.</a></td></tr>')
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                console.error(xhr.responseText);
                alert("Request to delete failed. Check the console for details.");
            }
        });
    }
</script>
